import axios from "axios";
import { notification, message } from "ant-design-vue";
import store from "../../store";
import defaultSetting from "./defaultSetting";
import utils from "./utils";

let BASE_URL = defaultSetting.requestDomain;

if (process.env.NODE_ENV === "development") {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    BASE_URL = BASE_URL + "/api";
  } else {
    BASE_URL = BASE_URL + "/selfApi";
  }
}

// 创建axios实例
const service = axios.create({
  // API 请求的默认前缀
  baseURL: BASE_URL,
  // 请求超时时间
  timeout: 30000,
});

/**
 * @description: 请求异常处理
 * @param {*} data 返回数据
 * @return {*}
 * @code    返回的状态码对应的类型:
 *          *1000 正常响应
 *          *1001 业务逻辑错误
 *          *1002 登录超时
 *          *1005 前端错误(缺少参数等)
 */

const errorHandler = (response) => {
  // 代码错误提示
  const errorNotification = (tip, errorLevel) =>
    notification[errorLevel]({
      message: errorLevel == "warning" ? "警告" : "错误",
      description: tip,
    });
  if (response.data) {
    const { code, msg, errorLevel } = response.data;
    const token = store.getters.token;
    switch (code) {
      case 1001:
        errorNotification(msg || "接口响应错误,请检查逻辑代码等!", errorLevel);
        break;
      case 1005:
        errorNotification(msg || "前端请求错误,请检查请求参数等!", errorLevel);
        break;
      case 1002:
        if (token) {
          message.warning("登录超时,请重新登录~");
        }
        break;
      case 1003:
        errorNotification(msg || "权限错误!", errorLevel);
        break;
      default:
        return Promise.reject(response.data);
    }
  } else {
    errorNotification("网络请求超时，请稍后再试!", "error");
    return Promise.reject(response);
  }
};

// request拦截器
service.interceptors.request.use((config) => {
  let token = store.getters.token;
  if (!token) {
    let sToken =
      utils.getStorage(`token`) ||
      localStorage.getItem(`${defaultSetting.from}_orgMain_org_token`) ||
      localStorage.getItem(`${defaultSetting.from}_systemMain_token`);
    if (sToken) {
      token = sToken;
      store.dispatch("SetToken", token);
    }
  }
  const mainAppName = store.getters.mainAppProps.mainAppName;
  const iframeData = store.getters.iframeData;
  if (token) {
    if (mainAppName) {
      const tokenPrefix = mainAppName.replace("Main", "");
      config.headers[`${tokenPrefix}-token`] = token;
    } else {
      if (iframeData.from) {
        config.headers[`${iframeData.from}-token`] = token;
      } else {
        config.headers["org-token"] = token;
        // config.headers["system-token"] = token;
      }
    }
  }
  const buildingInfo = store.getters.buildingInfo;
  if (buildingInfo.permissionBuildings) {
    config.headers["checked-build"] = JSON.stringify(
      buildingInfo.permissionBuildings
    );
  }
  return config;
}, errorHandler);

// response拦截器
service.interceptors.response.use((response) => {
  if (response.data) {
    const { code } = response.data;
    if (code === 1000) {
      return response.data;
    }
  }
  return errorHandler(response);
}, errorHandler);

const request = {
  BASE_URL,
  // get请求 server微服务 url 请求地址
  get(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .get(url, {
          params,
        })
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  //   post请求
  post(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .post(url, params)
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  //  put请求
  put(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .put(url, params)
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // delete请求
  del(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .delete(url, { data: params })
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
};

export default request;
